package com.example.netease.notepage;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private MyDatabaseHelper dbHelper;
    private SimpleAdapter simpleAdapter;
    private List<Map<String, String>> dataList;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 导航栏
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // 添加按钮
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                actionButtonClick(view);
            }
        });

        // 列表数据
        dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);

        // 初始化列表
        initListView();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    protected void onResume() {
        super.onResume();

        dataList.clear();

        List<DataModel> modelData = getModelData();
        List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        for (DataModel model : modelData) {
            Map<String, String> m = new HashMap<String, String>();
            m.put("title", model.content);

            m.put("info", formatTime(model.updateTime));
            m.put("id", model.id+"");

            dataList.add(m);
        }

        simpleAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String text = null;
            if (bundle != null)
                text = bundle.getString("content");
            Log.d("content", text);
        }
    }

    private void initListView() {
        dataList = new ArrayList<Map<String, String>>();
        listView = (ListView) findViewById(R.id.listView);
        simpleAdapter = new SimpleAdapter(this, dataList, R.layout.demo,
                new String[]{"title", "info"},
                new int[]{R.id.text1, R.id.text2});

        listView.setAdapter(simpleAdapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String, String> m = dataList.get((int) id);

                intoContentActivity(m.get("title"), m.get("id"));
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final Map<String, String> m = dataList.get((int) id);
                final long index = id;
                new AlertDialog.Builder(MainActivity.this).setItems(new String[] { "删除" }, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
                        String[] args = {String.valueOf(m.get("id"))};
                        sqliteDatabase.delete("book", "id=?", args);
                        dataList.remove(m);
                        simpleAdapter.notifyDataSetChanged();

                        Toast.makeText(MainActivity.this, "已删除" + m.get("id") , Toast.LENGTH_SHORT).show();
                    }
                }).show();

                return true;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void actionButtonClick(View view) {
        intoNewContentActivity();
    }

    private void intoNewContentActivity() {
        intoContentActivity("", "-1");
    }

    private void intoContentActivity(String content, String cid) {
        Intent intent = new Intent(MainActivity.this, DetailActivity.class);

        //用Bundle携带数据
        Bundle bundle = new Bundle();
        //传递name参数为tinyphp
        bundle.putInt("contentId", Integer.parseInt(cid));
        bundle.putString("content", content);
        intent.putExtras(bundle);

        startActivity(intent);
    }

    private String formatTime(Date date) {
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format1.format(date);
    }


    private List<DataModel> getModelData() {

        List<DataModel> data = new ArrayList<DataModel>();

        SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
        Cursor cursor = sqliteDatabase.query("book", new String[]{"id",
                "content", "updateTime", "createTime"}, null, null, null, null, "updateTime"+" DESC");

        while (cursor.moveToNext()) {
            DataModel model = new DataModel();
            model.id = cursor.getInt(cursor.getColumnIndex("id"));
            model.content = cursor.getString(cursor.getColumnIndex("content"));
            double updateTime = cursor.getDouble(cursor.getColumnIndex("updateTime"));
            double createTime = cursor.getDouble(cursor.getColumnIndex("createTime"));
            model.updateTime = new Date((long) updateTime);
            model.createTime = new Date((long) createTime);

            data.add(model);
        }

        return data;
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}
